// pages/article/article.js
const app = getApp()
let wxparse = require("../../wxParse/wxParse.js");
Page({

  /**
   * Page initial data
   */
  data: {
    content: {},
    dkheight: 50,
    dkcontent: "",
    close: true,
    answer: '',
    chi: '',
    title: '',
    show: false,
    dkcontent2: "",
    showIcon: true,
    touchS: [0, 0],
    touchE: [0, 0]
  },
  onClose() {
    // this.setData({
    //   show: false
    // });
    wx.showToast({
      title: '加载中请耐心等待..',
      icon: 'none'
    })
  },
  touchStart: function(e) {
    // console.log(e.touches[0].pageX)
    let sx = e.touches[0].pageX
    let sy = e.touches[0].pageY
    this.data.touchS = [sx, sy]
  },
  touchMove: function(e) {
    let sx = e.touches[0].pageX;
    let sy = e.touches[0].pageY;
    this.data.touchE = [sx, sy]
  },
  touchEnd: function(e) {
    let _this = this
    let start = this.data.touchS
    let end = this.data.touchE
    console.log(start)
    console.log(end)
    if (start[1] < end[1] - 2) {
      // console.log('下滑')
      _this.setData({
        showIcon: true
      })
    } else if (start[1] > end[1] + 1) {
      // console.log('上滑')
      _this.setData({
        showIcon: false
      })
    } else {
      _this.setData({
        showIcon: !_this.data.showIcon
      })
    }
  },
  /**
   * Lifecycle function--Called when page load
   */
  onLoad: function(options) {
    let _this = this
    wx.checkSession({
      success() {
        console.log('哟西')
        //session_key 未过期，并且在本生命周期一直有效
      },
      fail() {
        console.log('失效')
        // session_key 已经失效，需要重新执行登录流程
        _this.wxLogin() //重新登录

      },
      complete() {
        console.log('param', options)
        _this.setData({
          id: options.id
        })
        if (options.type != undefined) {
          _this.setData({
            type: options.type
          })
        }
        if (options.title != undefined) {
          _this.setData({
            title: options.title
          })
        }
        if (options.share != undefined) {
          _this.setData({
            share: options.share
          })
        }
        let winPage = _this;
        wx.getSystemInfo({
          success: function(res) {
            let winHeight = res.windowHeight;
            console.log(winHeight);
            winPage.setData({
              dkheight: winHeight - winHeight * 0.05 - 80
            })

          }

        })
        _this.getDetail(options.id)
      }
    })

    // 获得高度

  },
  findc(item) {
    let reg = /[\u4e00-\u9fa5]+\S?[\u4e00-\u9fa5]+/;
    let strs = item.trim().match(reg);
    let tar = strs[0]
    return tar
  },
  getDetail(id) {
    if (id == undefined) {
      wx.navigateBack();
    }
    let serverUrl = app.serverUrl
    let _this = this
    let _title = decodeURIComponent(_this.data.title)
    let url = `${serverUrl}/article/detail/${id}?title=${_title}&type=${_this.data.type}&share=${_this.data.share}`
    // let url = `http://localhost:888/article/detail/${id}`
    console.log('1')
    _this.setData({
      show: true
    })

    wx.request({
      header: app.globalData.header,
      url: url,
      method: "GET",
      success: function(res) {
        console.log("article", res)
        if (res.data.code == 0) {
          let content = res.data.content.content

          if (_this.data.type == 'ex') {
            let _content = res.data.content.content.replace('选择正确答案', '选择正确答<span><span/>案').replace('<div>参考答案:</div>', '!@#').replace('<div>参考答案如下:</div>', '!@#').replace(`<div>&nbsp;</div>
<div>&nbsp;</div>
<div>&nbsp;</div>
<div>&nbsp;</div>`, '!@#').replace('<div>答案：</div>', '!@#').replace('答案：', '!@#').replace('答案', '!@#')

            let body = _content.split('!@#')
            content = body[0]
            let answer = body[1]
            _this.setData({
              answer: answer
            })
            if (answer != undefined)
              wxparse.wxParse('answer', 'html', answer, _this, 5);

            console.log("answer::,", answer)


          }
          if (_this.data.type == 'trans') {
            let _content = res.data.content.content
            let tar = _this.findc(_content)
            if (tar != null && tar != '') {
              let body = _content.split(tar)
              content = body[0]
              if (content == null || content.trim() == "" || content.trim() == "<div>") {
                _this.setData({
                  close: false
                })
              }
              let chi = '<div><div>' + tar + body[1] + '</div>'
              console.log('chi', chi)
              _this.setData({
                chi: chi
              })
              wxparse.wxParse('chi', 'html', chi, _this, 5);

            }
          }
          _this.setData({
            content: content,
            title: res.data.content.title
          })
          wxparse.wxParse('dkcontent', 'html', res.data.content.title, _this, 15);
          wxparse.wxParse('dkcontent2', 'html', content, _this, 15);
          _this.setData({
            show: false
          })
        } else {}

      }
    })
  },
  /**
   * Lifecycle function--Called when page is initially rendered
   */
  onReady: function() {

  },

  /**
   * Lifecycle function--Called when page show
   */
  onShow: function() {

  },

  /**
   * Lifecycle function--Called when page hide
   */
  onHide: function() {

  },
  wxLogin() {

    let _this = this
    wx.login({
      success(res) {
        _this.setData({
          id: res.code
        })
        console.error('res.code', res.code)
        wx.getSetting({
          success: function(ret) {

            wx.getUserInfo({
              lang: "zh_CN",
              withCredentials: true,
              success: function(info) {
                console.log('res', info)
                let s = JSON.parse(info.rawData)
                console.error('s.avatarUrl', s.avatarUrl, s.nickName)
                console.error(s.avatarUrl == '')
                if (s.nickName != null && s.avatarUrl != null) {
                  let avatar = s.avatarUrl
                  avatar = s.avatarUrl == '' ? 'http://zzuisa.cn/unlogin.png' : s.avatarUrl
                  wx.request({
                    url: app.serverUrl + `/user/member/wxlogin`,
                    method: 'post',
                    data: {
                      code: res.code,
                      name: s.nickName,
                      headerImg: avatar,
                      gender: s.gender,
                      province: s.province,
                      city: s.city
                    },
                    success: function(reso) {
                      console.log('resooo', reso)
                      if (reso.data.code == 0) {
                        wx.hideLoading()
                        _this.setData({
                          userInfo: reso.data.content
                        })
                        app.setGlobalUserInfo(reso.data.content)
                        app.globalData.header.Cookie = reso.header["Set-Cookie"];
                        wx.hideLoading()
                        if (_this.data.page != undefined) {
                          let page = _this.data.page
                          wx.navigateTo({
                            url: decodeURIComponent(page.replace('article@', 'article?').replace('video@', 'video?'))
                          })
                        }
                      }

                    }
                  })
                }

              }
            })
          }
        })
      }
    })
  },
  /**
   * Lifecycle function--Called when page unload
   */
  onUnload: function() {

  },

  /**
   * Page event handler function--Called when user drop down
   */
  onPullDownRefresh: function() {

  },

  /**
   * Called when page reach bottom
   */
  onReachBottom: function() {

  },
  moveToLocation() {
    wx.navigateTo({
      url: '/pages/index/index',
    })
  },
  /**
   * Called when user click on the top right corner to share
   */
  onShareAppMessage(res) {

    let _this = this
    let page = _this.data.type == undefined ? `/pages/article/article@id=${_this.data.id}&title=${_this.data.title}&share=share` : `/pages/article/article@id=${_this.data.id}&title=${_this.data.title}&share=share&type=${_this.data.type}`
    return {
      title: `【德语助理】我分享了：${_this.data.title}，快来看看吧!`,
      path: `/pages/index/index?page=${page}`,
    }
  },
})